import 'package:flutter/material.dart';
import 'joke.dart';
import 'random_joke_state.dart';

class HomeView extends StatefulWidget {
  const HomeView({super.key});

  @override
  State<HomeView> createState() => _HomeViewState();
}

class _HomeViewState extends State<HomeView> {
  late final RandomJokeNotifier _notifier;

  @override
  void initState() {
    super.initState();
    _notifier = RandomJokeNotifier(fetchJoke: fetchRandomJoke);
  }

  @override
  void dispose() {
    _notifier.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _notifier,
      builder: (context, _) {
        final state = _notifier.state;

        return Scaffold(
          appBar: AppBar(title: const Text('Random Joke Generator')),
          body: SizedBox.expand(
            child: Stack(
              alignment: Alignment.center,
              children: [
                if (state.isRefreshing)
                  const Positioned(
                    top: 0,
                    left: 0,
                    right: 0,
                    child: LinearProgressIndicator(),
                  ),
                Builder(
                  builder: (context) {
                    if (state.isLoading && !state.hasJoke) {
                      return const CircularProgressIndicator();
                    }

                    if (state.hasError) {
                      return const Text('Error fetching joke');
                    }

                    if (state.hasJoke) {
                      final joke = state.joke!;
                      return SelectableText(
                        '${joke.setup}\n\n${joke.punchline}',
                        textAlign: TextAlign.center,
                        style: const TextStyle(fontSize: 24),
                      );
                    }

                    return const SizedBox.shrink();
                  },
                ),
                Positioned(
                  bottom: 20,
                  child: ElevatedButton(
                    onPressed: _notifier.refresh,
                    child: const Text('Get another joke'),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}
